#include<homeworkhead.h>
#include"threadPool.h"
#include"head.h"
#include"taskQueue.h"
int makeWorker(threadPool_t *pThreadPool){
    for(int i =0;i < pThreadPool->threadNum;++i){
        pthread_create(pThreadPool->tidArr+1,NULL,threadFunc,(void*)pThreadPool);
    }
}

int OrderJudge(task_t * pTask){
    char buf[1024]={0};
    if(strncmp(pTask->buf,"cd ",3)==0){
        cd(pTask);
    }
    else if(strncmp(pTask->buf,"cd",2)==0){
        cd(pTask);
    }
    else if(strncmp(pTask->buf,"ls ",3)==0){
        ls(pTask);
    }
    else if(strncmp(pTask->buf,"ls",2)==0){
        ls(pTask);
    }
    else if(strncmp(pTask->buf,"puts ",5)==0){
       //cd(pTask);
       uploadFile(pTask);
    }
    else if(strncmp(pTask->buf,"gets ",5)==0){
        //puts("gets");
        downloadFile(pTask);
    }
    else if(strncmp(pTask->buf,"remove ",7)==0){
        //puts("remove");
        removeFile(pTask);
    }
    else if(strncmp(pTask->buf,"pwd ",4)==0){
       printWorkingDir(pTask);
       //puts("pwd");
    }
    else if(strncmp(pTask->buf,"mkdir ",6)==0){
        myMkdir(pTask);
    }
    else if(strncmp(pTask->buf,"rmdir ",6)==0){
        //removeFile(pTask);
        puts("rmdir");
    }
    else{
        send(pTask->netFd,"命令错误，重新输入！",30,0);
        return -1;
    }
}
void *threadFunc(void *parg){
    threadPool_t *pThreadPool = (threadPool_t *)parg; //地址传递传入传出参数
    while (1){
        task_t *pTask;//新建一个task来接收队首的任务
        pthread_mutex_lock(&pThreadPool->mutex);
        while (pThreadPool->taskQueue.size == 0){
            pthread_cond_wait(&pThreadPool->cond,&pThreadPool->mutex);//解锁了等一个信号
        }
        puts("GetTask");//来信号了自动上锁
        pTask = pThreadPool->taskQueue.pFront;
        deQueue(&pThreadPool->taskQueue);
        pthread_mutex_unlock(&pThreadPool->mutex);
        printf("netFd = %d\n",pTask->netFd);
        handleEvent(pTask);
    }
}
int handleEvent(task_t * pTask){
    puts("welcome into handEvent!");
    int netFd = pTask->netFd;
    while (1){
        bzero(pTask->buf,sizeof(pTask->buf));
        int ret = recv(pTask->netFd,pTask->buf,sizeof(pTask->buf),0);
        if(ret == 0){
            puts("对面客户端断开！");
            break;
        }
        OrderJudge(pTask);
    }
    close(netFd);
    return 0;
}
